/*====================================== 
 author:faxsun
 Copyright © 2015 faxsun. All rights reserved. 
 如需修改请注意与页面标记类名相对应
 数据处理
 author:songdragon 2015-05-27 14:11
 文章提交
 ======================================*/
$(function() {
	/**
	 * 初始化控件
	 * 
	 */
	function initController() {
		var ueditor = null;
		if ($("#editor").length > 0) {
			ueditor = UE.getEditor('editor', {
				initialFrameWidth : 745
			});
		}
		loadHiddenFields(ueditor);
	}

	// 对于已有内容，从隐藏字段加载标签和编辑器内容
	function loadHiddenFields(ueditor) {
		if (ueditor != null && ueditor != 'undefined') {
			ueditor.ready(function() {
				var content = $('#content_temp').val();
				ueditor.setContent(content);
			});
		}
	}

	initController();

	/**
	 * 绑定事件
	 */
	if ($('#my_blog').length > 0) {
		$('#my_blog').submit(function(event) {
			var url = $('#my_blog').attr('action');
			event.preventDefault();
			// 检查提交内容
			var isValid = validateUserBlogForm();
			if (isValid) {
				$.post(url, $('#my_blog').serialize()).done(function(data) {
					var ret = JSON.parse(data);
					if (ret.code < 0) {
						alert(ret.message);
						if (ret.code == -2) {
							// 未登录
							$('#trigger-overlay').trigger('click');
						}
					} else if (ret.code == 0) {
						// 清空编辑器
						alert("提交成功！在通过审核前，您还可以继续编辑您提交的稿件！");
						window.location.href = '/faxsun-info/post/myblogs';
					} else {
						alert(ret.message);
					}
				});
			}
		});
	}
	
	$("body").on('click','#menu_post_save',function(event){
		$('#my_blog').submit();
	});
	
	$("body").on('click','#post_delete',function(event){
		event.preventDefault();
		deletePost();
	});

	/**
	 * Functions
	 */
	var validateUserBlogForm = function() {
		var title = $('#my_blog').find('input[name=title]').val();
		var content = $('#my_blog').find('input[name=content]').val();

		if (title == '') {
			alert('请输入标题');
			return false;
		} else if (content == '') {
			alert('请输入文章内容');
			return false;
		} else {
			return true;
		}

	}
	
	var deletePost=function(){
		var url=$('#post_delete').attr('href');
		$.get(url).done(function(data) {
			var ret = JSON.parse(data);
			if (ret.code < 0) {
				alert(ret.message);
				if (ret.code == -2) {
					// 未登录
					$('#trigger-overlay').trigger('click');
				}
			} else if (ret.code == 0) {
				// 清空编辑器
				alert("删除成功!");
				window.location.href = '/faxsun-info/post/myblogs';
			} else {
				alert(ret.message);
			}
		});
	}
});
